package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-09-01 20:54
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    //    操作es的工具类
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 保存商品上架功能数据到es
     *
     * @param skuEsModels
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) {
//            由于数据量庞大，每次保存到es会很慢，所以使用批量保存。(单条保存)
//            restHighLevelClient.index(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean b= false;
//        2、保存
        try {
            BulkRequest bulkRequest = new BulkRequest();
            for (SkuEsModel skuEsModel : skuEsModels) {
//              1、创建es索引名称,需要先在es中创建索引名称空间
                IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
//                2.1、es保存的id
                indexRequest.id(skuEsModel.getSkuId().toString());
//                2.2、保存的数据
                String jsonString = JSON.toJSONString(skuEsModel);
                indexRequest.source(jsonString, XContentType.JSON);
//                2.3、添加到bulkRequest中
                bulkRequest.add(indexRequest);
            }
//            bulk(BulkRequest bulkRequest, RequestOptions options) （批量保存）
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
//            批量保存完成之后可以得到是否有错误(true--有错误。false--无错误)
            b = bulk.hasFailures();
//            得到具体某一条数据保存错误
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("商品上架完成：{}", collect);


        } catch (Exception e) {
            log.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
            e.printStackTrace();
        }
        return b;
    }
}
